const app = getApp()
Page({
  data: {
    editimage: {},//编辑图片信息
    delimagedetail: {},
    address:'',//丢失地址
    push: '推送',//推送按钮
    now_detail: {},
    phototitle: '',
    photodetaildata: [],
    photolistdata: {},//相册记录
    page: 1,
    isBottom: false,//是否加载
    isphotodata: false,//相册是否有数据
    nodata: false,//显示没有数据
    showbottom: false,//显示到底部
    loadingHidden: false,//代表出现加载
    user_id: '',
    parentrole: 'hide',//家长首页
    classmaster: 'hide',//班主任标志
    workmasktype: 'hide',//作业遮罩
    photomasktype: 'hide',//相册遮罩
    isbind: false,
    userInfo: [],
    imglimit: 1,
    dispaly: 'hide',
    content: '',
    current: 0,
    max: 300,
    jia: 'show',
    role: '',//3为家长角色 1为班主任
    hasUserInfo: true,
    tabArr: {
      curHdIndex: 2,// tab 切换 .默认为相册，作业暂时取消
    },
    submitdata: {
      img_src: '',
      imagelist: {}
    },
    addimage: [],//作业数据
    uplocaimage: {},
    phptoInfo: {
      avatarUrl: [
        'https://p3.pstatp.com/large/31fa0003ed7228adf421',
      ],
      imgUrls: [
        'https://p3.pstatp.com/large/31fa0003ed7228adf421',
        'https://p3.pstatp.com/large/39f600038907bf3b9c96',
        'https://p3.pstatp.com/large/31fa0003ed7228adf421'
      ],
    },
  },

  //编辑图片
  changeimage: function (event) {
    var sort = event.currentTarget.dataset.sort;//获取data-src
    var detail = event.currentTarget.dataset.detail;
    var img_src = event.currentTarget.dataset.src;
    var count = this.data.submitdata.imagelist.length;
    if (detail == undefined || detail == null) {
      detail = "";
    }
    if (img_src == undefined || img_src == null) {
      img_src = "";
    }
    if (sort == undefined || sort == null) {
      sort = 0;
    }
    wx.navigateTo({
      url: '../found/editimg?count=' + count + '&sort=' + sort + '&img_src=' + img_src + '&detail=' + detail
    })
  },
  //限制300字数
  addresslimit: function (event) {
    var value = event.detail.value;
    var length = parseInt(value.length);
    if (length > 100) {
      wx.showToast({
        title: '不超过100字',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    this.setData({
      address: value
    });
  },
 
  //获取数据列表 失物招领
  getLocation: function (options) {
    var page = options;
    var that = this;
    var openid = app.globalData.openid;
    var link = app.globalData.schlink;
    var user_id = app.globalData.bindInfo.user_id;
    wx.request({
      url: getApp().globalData.baseUrl + 'lostrecord',
      data: {
        link: link,
        openid: openid,
        page: page,
        cid:7,
        limit:10
      },
      method: "get",
      header: {},
      success: function (res) {
        // console.log(res);return;
        if (res.data.code == 200) {
          var resultdata = res.data.data.data;
          var count = res.data.data.count;//相册记录条数
          if (count > page * 10) {
            that.setData({ isBottom: true });//多于10条数据
          } else {
            that.setData({ isBottom: false });
          }
          if (resultdata.length > 0) {
            that.setData({ isphotodata: true });
            that.setData({ count: count });
            var arr = [];
            if (page > 1) {
              var photolistdata = that.data.photolistdata;
              arr = photolistdata.concat(resultdata);
              that.setData({ photolistdata: arr });
            } else {
              that.setData({ photolistdata: resultdata });
            }
          } else {
            that.setData({ nodata: true });//没有数据
            that.setData({ isphotodata: true });
          }
        }
        that.setData({ loadingHidden: true });
      }
    })
  },

  //功能上传数据
  submitdata: function (event) {
    if (this.data.user_id == "" || this.data.user_id == undefined) {
      wx.showToast({
        title: '用户信息丢失,请联系管理员',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    var postdata = {};
    postdata.imagelist = this.data.addimage;
    postdata.content = this.data.content;
    var that = this;
    wx.request({
      url: 'https://mapp.wzzd.cn/uploadwork',
      data: postdata,
      method: "post",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'succes',
            duration: 1500,
            mask: true
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          })
        }
        setTimeout(function () {
          that.setData({ workmasktype: 'hide' });
          that.setData({ photomasktype: 'hide' }); //关闭相册弹窗
          that.setData({ parentrole: 'show' });//打开班主任首页
        }, 1500)
      }
    })
  },

  //功能上传数据提交提交数据 cid=7 
  phptosubmitdata: function (event) {
    var avatarUrl = '';//微信头像
    if (app.globalData.userInfo) {
      var avatarUrl = app.globalData.userInfo.avatarUrl;
    } else {
      if (app.globalData.bindInfo) {
        var avatarUrl = app.globalData.bindInfo.user_avatar;
      }
    }
    var address = this.data.address;
    if (address == undefined || address==null){
      address="";
    }
    var user_id = app.globalData.bindInfo.user_id;
    var link = app.globalData.schlink;
    if (user_id == "" || user_id == undefined || user_id == null) {
      wx.redirectTo({
        url: '../binding/binding'
      })
    }
    var submitdata = this.data.submitdata;//提交的数据
    var items = [];
    for (let i in submitdata.imagelist) {
      if (i == undefined || i == "undefined") {
      } else {
        items.push(submitdata.imagelist[i]);
      }
    }
    items = JSON.stringify(items);
    if (this.data.phototitle == "" || this.data.phototitle == null || this.data.phototitle == undefined) {
      wx.showToast({
        title: '标题不为空',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    var that = this;
    wx.request({
      url: getApp().globalData.baseUrl + 'uploadLostdata',
      data: {
        user_id: this.data.user_id,
        type: "image",
        cid: 7,//失物
        caption: this.data.phototitle,
        openid: app.globalData.openid,
        avatarUrl: avatarUrl,
        imagelist: submitdata.imagelist,
        img_src: submitdata.img_src,
        imagelist: items,
        link: link,
        address: address,
      },
      method: "post",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        // console.log(res);return;
        that.getLocation(1);//重新请求记录
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'succes',
            duration: 1500,
            mask: true
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          })
        }
        setTimeout(function () {
          that.setData({ photomasktype: 'hide' }); //关闭相册弹窗
          that.setData({ parentrole: 'show' });//打开班主任首页
          that.setData({ phototitle: '' });//清空数据
          that.setData({ 'submitdata.img_src': '' });//清空数据
          that.setData({ 'submitdata.imagelist': [] });//清空数据
          that.setData({ address:''});//清空数据
        }, 1500)
      }
    })
  },
  //删除图片
  delimage: function (event) {
    var that = this;
    var idx = event.currentTarget.dataset.idx;
    var addimage = that.data.addimage;
    var filterRes = addimage.filter((ele, index) => {
      return index != idx
    })
    if (filterRes.length < 9) {
      that.setData({ jia: 'show' });
    }
    that.setData({
      addimage: filterRes,
    });
  },
  //删除相册记录
  deldata: function (event) {
    var user_id = app.globalData.bindInfo.user_id;
    var openid = app.globalData.openid;
    var link = app.globalData.schlink;
    var that = this;
    var id = event.currentTarget.dataset.idx;
    var sort = event.currentTarget.dataset.sort;
    if (user_id == "" || user_id == null || user_id == undefined) {
      return;
    }
    if (id == "" || id == null || id == undefined) {
      return;
    }
    wx.showModal({
      title: '确定删除此记录?',
      content: '',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: getApp().globalData.baseUrl + 'delphotodata',
            data: {
              id: id,
              user_id: user_id,
              link: link,
              openid: openid
            },
            method: "post",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"  //post
            },
            success: function (res) {
              if (res.data.code == 200) {
                var photolistdata = that.data.photolistdata;
                photolistdata.splice(sort, 1);
                that.setData({
                  photolistdata: photolistdata,
                });
                wx.showToast({
                  title: '删除成功',
                  icon: 'succes',
                  duration: 1500,
                  mask: true
                })
              }
            }
          })
        }
      }
    })
  },

  //删除相册 至少保留一张
  delphotodata: function (event) {
    var that = this;
    var index = event.currentTarget.dataset.sort;
    var submitdata = that.data.submitdata;
    if (submitdata.imagelist.length <2){
      wx.showToast({
        title: '至少保留一张',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    submitdata.imagelist.splice(index, 1);
    that.setData({
      submitdata: submitdata,
    });
  },
  upload: function () {
    for (var i = 0; i < this.data.submitdata.imagelist; i++) {
      this.upload_file(this.data.submitdata.imagelist[i])
    }
  },
  //调取相机 如果是相册上传。只能限制一张图片
  handlePhoto: function (options) {
    var that = this;
    var imglimit = that.data.imglimit;
    var now_role = that.data.role;
    var curHdIndex = that.data.tabArr.curHdIndex;
    var addimage = that.data.addimage;
    if (addimage.length > 0) {
      imglimit = imglimit - addimage.length;
    }
    var uplocaimage = that.data.uplocaimage;
    wx.chooseImage({
      count: imglimit, // 默认1
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({ loadingHidden: false });
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var serviceimage = [];
        if (tempFilePaths.length > 0) {
          for (var i = 0; i < tempFilePaths.length; i++) {
            var num = i;
            wx.uploadFile({
              url: app.globalData.baseUrl + 'wxuploadimage',
              filePath: tempFilePaths[i],
              name: 'file',
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: function (res) {
                that.setData({ loadingHidden: true });
                var obj = JSON.parse(res.data);
                if (obj.code == 200) {
                  var arr = [];
                  var uploadsrc = obj.data;//图片服务器路径
                  arr.push(uploadsrc);
                  if (curHdIndex == 2) {
                    that.setData({ workmasktype: 'hide' });//隐藏作业
                    that.setData({ photomasktype: 'show' });//打开相册上传遮罩层
                    //相册文字详情数组默认封面设置
                    var obj = {};
                    obj.img_src = uploadsrc;
                    obj.detail = '';
                    obj.sort = 0;
                    that.setData({ photodetaildata: obj });
                    that.setData({ 'submitdata.img_src': uploadsrc });
                    that.setData({ 'submitdata.imagelist[0]': obj });
                  }
                }
              }
            })
          }
          that.setData({ parentrole: 'hide' });
        }
      }
    })
  },
  //修改封面相机
  facehandlePhoto: function (limit, sort) {
    var that = this;
    var limit = limit;//张数
    var sort = sort;
    wx.chooseImage({
      count: limit,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        if (tempFilePaths.length > 0) {
          for (var i = 0; i < tempFilePaths.length; i++) {
            var num = i;
            wx.uploadFile({
              url: app.globalData.baseUrl + 'wxuploadimage',
              filePath: tempFilePaths[i],
              name: 'file',
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: function (res) {
                var resobj = JSON.parse(res.data);
                if (resobj.code == 200) {
                  var arr = [];
                  var src = resobj.data;
                  arr.push(src);
                  var img_src = '';
                  var submitdata = that.data.submitdata;
                  var obj = {};
                  obj.img_src = arr[0];
                  obj.detail = '';
                  obj.sort = sort;
                  if (sort == 'face') {
                    if (tempFilePaths.length > 0) {
                      that.setData({ 'submitdata.img_src': arr[0] });
                    }
                  }
                  if (sort >= 0) {
                    submitdata.imagelist.splice(sort + 1, 0, obj);
                    that.setData({ submitdata: submitdata });
                  }
                  if (sort == 'top') {
                    submitdata.imagelist.splice(0, 0, obj);//数组头部插入数据
                    that.setData({ submitdata: submitdata });
                  }
                }
              }
            })
          }
        }
      }
    })
  },
  fail: function (res) {
  },
  //限制300字数
  limit: function (event) {
    var value = event.detail.value;
    var length = parseInt(value.length);
    if (length > this.data.max) {
      return;
    }
    this.setData({
      current: length,
      content: value
    });
  },
  //预览上传的图片
  imgYu2: function (event) {
    var addimage = this.data.addimage;
    var src = event.currentTarget.dataset.src;//获取data-src
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: addimage  // 需要预览的图片http链接列表
    })
  },
  //预览作业记录图片
  showwork: function (event) {
    var phptoInfo = this.data.phptoInfo.imgUrls;
    var src = event.currentTarget.dataset.src;//获取data-src
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: phptoInfo  // 需要预览的图片http链接列表
    })
  },


  //查看详情
  seedetail: function (e) {
    var dataId = e.currentTarget.dataset.idx;
    wx.navigateTo({
      url: '../classcard/photodetail?id=' + dataId
    })
  },

  //推送数据到班牌
  pushdata: function (event) {
    var openid = app.globalData.openid;
    var link = app.globalData.schlink;
    var that = this;
    var dataId = event.currentTarget.dataset.idx;
    var user_id = app.globalData.bindInfo.user_id;
    if (app.globalData.bindInfo.classmaster == "" || app.globalData.bindInfo.classmaster == null || app.globalData.bindInfo.classmaster == undefined) {
      wx.showToast({
        title: '不是班主任,没有权限',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    if (user_id == "") {
      wx.showToast({
        title: '网络卡顿',
        icon: 'error',
        duration: 1500,
        mask: true
      })
    }
    wx.request({
      url: getApp().globalData.baseUrl + 'pushdata',
      data: {
        openid: openid,
        link: link,
        id: dataId,
        user_id: user_id
      },
      method: "post",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"  //post
      },
      success: function (res) {
        that.getLocation(1);
        if (res.data.code == 200) {
          wx.showToast({
            title: '推送成功',
            icon: 'succes',
            duration: 1500,
            mask: true
          })
        } else {
          wx.showToast({
            title: '推送失败',
            icon: 'none',
            duration: 1500,
            mask: true
          })
        }
      }
    })
  },
  //tab切换
  handleTab: function (e) {
    var dataId = e.currentTarget.id;
    var obj = {};
    obj.curHdIndex = dataId;
    this.setData({
      tabArr: obj
    })
  },

  //设置标题
  settitle: function (e) {
    var title = this.data.phototitle;
    wx.navigateTo({
      url: '../classcard/settitle?title=' + title
    })
  },
  //设置封面
  setface: function (e) {
    this.facehandlePhoto(1, 'face');
  },
  //相册第一个
  addtop: function (e) {
    this.facehandlePhoto(1, 'top');
  },

  //添加相册
  addphoto: function (event) {
    var sort = event.currentTarget.dataset.sort;//获取data-src
    this.facehandlePhoto(1, sort);
  },
  //添加文字
  adddetail: function (event) {
    var sort = event.currentTarget.dataset.sort;//获取data-src
    var detail = event.currentTarget.dataset.detail;
    var img_src = event.currentTarget.dataset.src;
    this.setData({ 'now_detail.sort': sort });
    if (detail == undefined || detail == null) {
      detail = "";
    }
    if (img_src == undefined || img_src == null) {
      img_src = "";
    }
    if (sort == undefined || sort == null) {
      sort = 0;
    }
    wx.navigateTo({
      url: '../classcard/addtext?detail=' + detail + '&sort=' + sort + '&img_src=' + img_src
    })
  },

  //相册取消
  photocancelbutton: function (e) {
    var that = this;
    that.setData({ parentrole: 'show' });
    that.setData({ photomasktype: 'hide' });//关闭相册遮罩
    that.setData({ workmasktype: 'hide' });//关闭作业遮罩
    that.setData({ phototitle: '' });//标题为空
    that.setData({ 'submitdata.imagelist': [] });
    that.setData({ 'submitdata.img_src': '' });
    var obj = {};
    that.setData({ now_detail: obj });
  },
  binduser: function (e) {
    wx.navigateTo({
      url: '../binding/binding'
    })
  },

  //初加载
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "失物招领"
    })
    var that = this;
    if (app.globalData.bindInfo) {
      that.getLocation(1);//获取相册记录列表
      this.setData({ parentrole: 'show' });
      this.setData({
        isbind: true,
        user_id: app.globalData.bindInfo.user_id
      })
      if (app.globalData.bindInfo.user_type == 1) {
        this.setData({//班主任
          role: 1
        })
      }
      if (app.globalData.bindInfo.classmaster > 0) {
        this.setData({
          classmaster: 'show'
        })
      }
      if (app.globalData.bindInfo.user_type == 3) {
        this.setData({
          role: 3
        })
      }
    } else {
      wx.navigateTo({
        url: '../binding/binding'
      })
    }

    if (app.globalData.userInfo) {
      
    } else {
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  onShow: function () {
    var that = this;
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    
    if (currPage.data.title) {
      that.setData({ title: currPage.data.title });//标题
    }

    if (Object.keys(currPage.data.editimage).length > 0) {
      var submitdata = that.data.submitdata;
      var sort = parseInt(currPage.data.editimage.sort);
      var arr = currPage.data.editimage;
      submitdata.imagelist[sort].img_src = arr.img_src;
      that.setData({ submitdata: submitdata });
      currPage.data.editimage = {};
    }

    if (Object.keys(currPage.data.delimagedetail).length > 0) {
      var submitdata = that.data.submitdata;
      var sort = parseInt(currPage.data.delimagedetail.sort);
      if (currPage.data.delimagedetail.detail == "" || currPage.data.delimagedetail.detail == null || currPage.data.delimagedetail.detail == undefined) {
        //全部删掉
        submitdata.imagelist.splice(sort, 1);
        that.setData({ submitdata: submitdata });
        currPage.data.delimagedetail = {};
      } else {
        submitdata.imagelist[sort] = currPage.data.delimagedetail;
        that.setData({ submitdata: submitdata });
        currPage.data.delimagedetail = {};
      }
    }


    if (Object.keys(currPage.data.now_detail).length > 0) {
      var submitdata = that.data.submitdata;
      if (currPage.data.now_detail.detail == "" || currPage.data.now_detail.detail == undefined || currPage.data.now_detail.detail == null) {
        for (let i in submitdata.imagelist) {
          if (i == currPage.data.now_detail.sort) {
            submitdata.imagelist[i].detail = "";
          }
        }
        that.setData({ submitdata: submitdata });
      } else {
        var sort = currPage.data.now_detail.sort;
        submitdata.imagelist[sort] = currPage.data.now_detail;
        that.setData({ submitdata: submitdata });
      }
      currPage.data.now_detail = {};
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },
  onReachBottom: function () {
    var data = this.data.photolistdata;
    var count = this.data.count;
    var isBottom = this.data.isBottom;
    if (!isBottom) {
      this.setData({ showbottom: true });
      return;
    }
    var that = this;
    var page = this.data.page;
    page = page + 1;
    that.getLocation(page);
  },
  onShareAppMessage: function () {
  }
})